﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using LogikBug.ModularMvc;
using Test.Entities;
using Test.Modules.Accounts.ClientBilling.Models;

namespace Test.Modules.Accounts.ClientBilling.Controllers
{
	[Authorize]
	public class AccountController : Controller
	{
		private static IModuleProvider Provider
		{
			get
			{
				return ModuleProvider.Current;
			}
		}

		public ActionResult Payment()
		{
			return View();
		}

		public ActionResult Usage()
		{
			return View();
		}

		[HttpGet]
		public ActionResult Manage()
		{
			return View(new AccountModuleListViewModel(GetWebsiteModules()));
		}

		[HttpPost]
		public ActionResult Manage(FormCollection collection)
		{
			foreach (var key in collection.Keys)
			{
				bool enabled;

				if (!Provider.HasModule(key) || !Provider[key].IsOptional)
				{
					continue;
				}

				if (!bool.TryParse(collection[key.ToString()], out enabled))
				{
					enabled = true;
				}

				Provider[key].IsEnabled = enabled;
			}

			return View(new AccountModuleListViewModel(GetWebsiteModules()));
		}

		private static IEnumerable<WebsiteModule> GetWebsiteModules()
		{
			return Provider.OfType<IVisualModule>().Select(m => new WebsiteModule
			{
				Name = m.Name,
				Id = m.GetType().GUID,
				Key = m.Key.ToString(),
				Enabled = m.IsEnabled,
				Optional = m.IsOptional,
				Location = m.Assembly.Location
			});
		}
	}
}